package middleware

import (
    "errors"
    "github.com/gin-gonic/gin"
    "gonaio_base/service"
    "net/http"
)

func NewJWT(key string, expireTime int64, m map[string]string) gin.HandlerFunc {
    return func(c *gin.Context) {
        if c.Request.URL.Path == "/favicon.ico" {
            c.Next()
            return
        }
        if v, ok := m[c.Request.URL.Path]; ok && c.Request.Method == v {
            c.Next()
            return
        } else {
            token := c.Request.Header.Get("authorization")
            jwtInstance := bservice.New().GetJWT().SetConfig(key, expireTime)
            result, err := jwtInstance.Parse(token)
            if err == nil {
                c.Set("token_parse", result)
                c.Next()
                return
            } else {
                c.AbortWithError(http.StatusUnauthorized, errors.New("token error"))
            }
        }
    }
}
